package com.zzty.train.pjm.util;

import com.alibaba.fastjson.JSONObject;
import com.zzty.train.pjm.entity.User;
import net.sf.json.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.List;


public class HttpUtil {


    public static String httpPostWithJSON(String url,String str) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;

//        json方式
        StringEntity entity = new StringEntity(str,"utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");

        httpPost.setEntity(entity);
        System.out.println();

        HttpResponse resp = client.execute(httpPost);
        if(resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he,"UTF-8");
        }
        return respContent;
    }

    public static String httpGet(String url) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpGet hg = new HttpGet(url);

        //3.执行
        HttpResponse response = client.execute(hg);

        //4.判断返回码
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            //5.得到结果
            HttpEntity result = response.getEntity();

            //转换成string类型
            String str = EntityUtils.toString(result);

            return str;
        }
        return null;
    }




    public static void main(String[] args) throws Exception {
//        String u=httpGet("http://localhost/getUserById/"+1);
//        User user1=JSONObject.parseObject(u,User.class);
//        System.out.println("user1 "+user1);

//        String us=httpGet("http://localhost/list");
//        List<User> users=JSONObject.parseArray(us,User.class);
        User user=new User();
        user.setName("aaa");
        String result = httpPostWithJSON("http://localhost:8888/user/addUser",user.toString());
        //String result1=httpGet("http://localhost:8888/user/addUser"+"/"+user.toString());
        System.out.println("result"+result);
        JSONObject demoJson =  JSONObject.parseObject(result);
        System.out.println("demoJson "+demoJson);
        String resul = demoJson.getString("result");
        System.out.println(resul);
    }
}
